package com.ruoyi.test.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.stereotype.Service;


@Service
public class DriverGeoService {
    private static final String LOCATION_KEY = "driver:locations";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 使用 Geohash 算法将经纬度转换为分数（模拟 GEOADD）
     */
    public void addUserLocation(String userId, double longitude, double latitude, String locationName) {
        String member = userId + ":" + locationName;

        // 删除已存在的成员（避免重复）
        redisTemplate.opsForGeo().remove(LOCATION_KEY, member);

        // 添加新位置
        redisTemplate.opsForGeo().add(LOCATION_KEY,
                new Point(longitude, latitude),
                member
        );
    }

    /**
     * 计算两点距离
     * @param location1
     * @param location2
     * @return
     */

    public double getDistanceBetweenPoints(String location1, String location2) {
        Distance distance = redisTemplate.opsForGeo().distance(
                LOCATION_KEY,
                location1,
                location2,
                Metrics.METERS
        );

        return distance != null ? distance.getValue() : -1;
    }
}